package cn.edu.zju.qsc.rouchseg.segment;

import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.edu.zju.qsc.rouchseg.tools.FileTool;

public class DefaultSeg {
	private List<String> allDicWords;
	private Map dic;
	private Map reverseDic;
	
	private Seg segment;
	
	public DefaultSeg(String filename) {
		this.segment = new Seg();
		if (filename != null && filename.isEmpty() == false) {
			try {
				this.allDicWords = FileTool.readDicFile(filename);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			this.dic = this.segment.loadDic(this.allDicWords);
			this.segment.setReverse(true);
			this.reverseDic = this.segment.loadDic(this.allDicWords);
			this.segment.setReverse(false);
		}
	}
	
	public List<String> cut(String text){
		List result = null;
		
		segment.setReverse(false);
		segment.setDicMap(this.dic);
		segment.doSeg(text);
		segment.combineResult(false);	/** 单字成词个数以原始为准 */
		List<String> words = new ArrayList<String>(segment.getResult());
		int singleWordNum = new Integer(segment.getSingleWordNum());
		int longWordNum = new Integer(segment.getLongWordNum());
		
		segment.setReverse(true);
		segment.setDicMap(this.reverseDic);
		segment.doSeg(text);
		segment.combineResult(false);	/** 单字成词个数以原始为准 */
		List<String> reverseWords = new ArrayList<String>(segment.getResult());
		int reverseSingleWordNum = new Integer(segment.getSingleWordNum());
		int reverseLongWordNum = new Integer(segment.getLongWordNum());
		
		if (longWordNum > reverseLongWordNum) {
			result = words;
		} else if (longWordNum < reverseLongWordNum) {
			result = reverseWords;
		} else {
			/** 长词个数相等则比较词长 */
			if (words.size() > reverseWords.size()) {
				result = reverseWords;
			} else if (words.size() < reverseWords.size()) {
				result = words;
			} else {
				/** 相等则比较单字成词的个数 */
				if (singleWordNum > reverseSingleWordNum) {
					result = reverseWords;
				} else {
					result = words;
				}
			}
		}
		return result;
	}
}
